package oog.product.control;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oog.product.ReqUtil;
import oog.product.Util;
import oog.product.biz.ProductBiz;
import oog.product.entity.MyUser;
import oog.product.form.ProductForm;

/**
 * Servlet implementation class AddServlet
 */
public class AddServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    super.service(request, response);
	    String nextPage = PAGE_PRODUCT_ADD; // default, re-display the Product Add page
	    ProductForm form = (ProductForm) ReqUtil.parseRequest(request, ProductForm.class);
		List<String> errorList = null;
		
		if ("Add".equals(form.getCmd())) {
		    errorList = validate(form);
		    if (Util.isNNandNB(errorList)) { // Has error
		        request.setAttribute(KEY_ERRORLIST, errorList);
		    } else { // No error in form
		        session = request.getSession();
		        MyUser logonUser = (MyUser) session.getAttribute(KEY_USER);
		        if (logonUser == null) {
		            errorList = new ArrayList<String>();
		            errorList.add("The session is invalid!");
		            request.setAttribute(KEY_ERRORLIST, errorList);
		        } else {
		            ProductBiz biz = new ProductBiz(logonUser);
		            if (biz.save(form)) { // save successful
		                request.setAttribute(KEY_MESSAGE, "Save succesfully.");
		            } else {
	                    errorList = new ArrayList<String>();
	                    errorList.add("Error during store the product!");
	                    request.setAttribute(KEY_ERRORLIST, errorList);
	                }
		        }
		    }
		} else if ("Back".equals(form.getCmd())) {
		    nextPage = PAGE_PRODUCT_SEARCH;
		} else { // Initial the Add screen
		    nextPage = PAGE_PRODUCT_ADD;
		}
		// Keep the form in the request
		request.setAttribute(KEY_FORM, form);
		request.getRequestDispatcher(nextPage).forward(request, response);
	}


    private List<String> validate(ProductForm form) {
        return null;
    }

}
